package com.coolw.test.sftp;

import com.jcraft.jsch.*;

/**
 * sftp 客户端
 *
 * @author coolw
 * @date 2023/11/17 10:11
 */
public class SftpClient {

    Session session = null;
    Channel channel = null;

    private final String host = "127.0.0.1";
    private final int port = 22;
    private final String username = "coolw";
    private final String password = "123456";
    private final int timeout = 60000;

    public ChannelSftp getChannel() throws JSchException {
        JSch jSch = new JSch();

        // 新建会话
        session = jSch.getSession(username, host, port);
        session.setPassword(password);
        session.setTimeout(timeout);
        // 跳过第一次连接时的确认提示
        session.setConfig("StrictHostKeyChecking", "no");
        session.connect();

        // 获取通信通道
        Channel channel = session.openChannel("sftp");
        channel.connect();

        return (ChannelSftp) channel;
    }

    public void closeChannel() {
        if (channel != null) {
            channel.disconnect();
        }
        if (session != null) {
            session.disconnect();
        }
    }
}
